package cn.tedu.charging.order.config;

import cn.tedu.charging.order.dao.mapper.OrderSuccessMapper;
import cn.tedu.charging.order.mqtt.MqttConsumer;
import cn.tedu.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Random;

@Configuration
public class MqttConfiguration {

    @Autowired
    private MqttContext mqttContext;

    @Autowired
    OrderSuccessMapper orderSuccessMapper;

    private String host = "tcp://127.0.0.1:1883";

    private String username = "admin";

    private String password = "public";

    /**
     * 客户端 启动多个订单服务,需要保证每个订单服务的clientId 不同
     */
    private String clientId = "order_service_client" + getRandom();

    private Integer getRandom() {
        return  new Random().nextInt(10000);
    }

    @Bean
    public MqttClient mqttClient() throws MqttException {

        /**
         * 通过连接地址和clientId 进行连接
         */
        MqttClient mqttClient = new MqttClient(host, clientId);

        /**
         * 连接相关的配置
         */
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setUserName(username);
        connOpts.setPassword(password.toCharArray());
        //清理会话session
        connOpts.setCleanSession(true);
        //自动重连
        connOpts.setAutomaticReconnect(true);
        //版本号设置
        connOpts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);

        //mqttConsumer 是通过 new 的方式创建的,没有在Spring容器里
        //MqttClient 是通过@Bean的方式 创建的,在Spring容器里
        //没有在Spring容器里的mqttConsumer 想使用 在Spring容器里 MqttClient 来订阅topic
        MqttConsumer mqttConsumer = new MqttConsumer(mqttContext,mqttClient,orderSuccessMapper);
        //mqttConsumer.setMqttClient(mqttClient);
        mqttClient.setCallback(mqttConsumer);

        //connect mqttClient的连接方法,基于配置 connOpts 和 EMQX 进行连接
        mqttClient.connect(connOpts);

        return mqttClient;
    }


}
